package com.yurun.orderservice.tcc;

import com.alibaba.fastjson.JSONObject;
import com.yurun.domain.OrderTb;
import com.yurun.orderservice.mapper.OrderTbMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author Xi Gao
 * @date 2020/9/13 11:55
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class OrderActionServiceImpl implements OrderActionService {
    @Resource
    private OrderTbMapper orderTbMapper;

    @Override
    public boolean saveOrder(BusinessActionContext context, OrderTb orderTb) {
        log.info("准备阶段封装order:{}", orderTb);
        ResultHolder.setResult(getClass(), context.getXid(), "T");
        return true;
    }

    /**
     * 提交失败会重试
     *
     * @param context
     * @return
     */
    @Override
    public boolean mycommit(BusinessActionContext context) {
        log.info("commit=====start");
        if (ResultHolder.getResult(getClass(), context.getXid()) == null) {
            return true;
        }
        OrderTb orderInfo = JSONObject.parseObject(((JSONObject) context.getActionContext("orderInfo")).toJSONString(), OrderTb.class);
        ;
        orderTbMapper.insert(orderInfo);
        //提交失败怎么办 ？？
        ResultHolder.removeResult(getClass(), context.getXid());
        log.info("commit====end");
        return true;
    }

    @Override
    public boolean myrollBack(BusinessActionContext context) {
        log.info("rollbck=====start");
        if (ResultHolder.getResult(getClass(), context.getXid()) == null) {
            return true;
        }
        ResultHolder.removeResult(getClass(), context.getXid());
        log.info("rollbck=====end");
        return true;
    }
}
